/*
 *  Copyright (C) 2010 Francesco Boffa (aka AlfaOmega08)
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package Gui;

import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import javax.swing.ButtonGroup;

public class MainFrame extends javax.swing.JFrame {
	ButtonGroup LanguageGroup = new ButtonGroup();
	ResourceBundle translations;
	Languages lang = new Languages();
	Engine.Ps1 PlayStation;

	public MainFrame() {
		ReadCfg();

		initComponents();
		lang.InitMenu(MenuLanguage);

		ActionListener LanguageListener = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Engine.Config.setConfig("LongLanguage", e.getActionCommand());
				Engine.Config.setConfig("Language", lang.getLanguage(e.getActionCommand()));
				Engine.Config.setConfig("Country", lang.getCountry(e.getActionCommand()));

				LoadLocale();
			}
		};

		lang.setActionListeners(LanguageListener);

		LoadRecentImages();
		LoadLocale();
	}

	private void ReadCfg() {
		File cfgFile = new File("pps1e.cfg");

		/* Load the config with default values */
		Engine.Config.Init();

		/* If a config file is present, load its values in the config */
		try {
			ParseCfg(cfgFile);
		} catch (FileNotFoundException e) {
		}
	}

	private void ParseCfg(File f) throws FileNotFoundException {
		BufferedReader input = new BufferedReader(new FileReader(f));

		try {
			try {
				String line;
				Pattern p = Pattern.compile("([A-Za-z0-9\\-_]+)=(.*)");
				while ((line = input.readLine()) != null) {
					Matcher m = p.matcher(line);

					Boolean ok = m.find();
					if (!ok) {
						return;
					}

					Engine.Config.setConfig(m.group(1), m.group(2));
				}
			} finally {
				input.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void LoadLocale() {
		Locale locale = new Locale(Engine.Config.getConfig("Language"), Engine.Config.getConfig("Country"));
		translations = ResourceBundle.getBundle("Translations/Messages", locale);

		MenuFile.setText(translations.getString("MenuFile"));
		MenuEdit.setText(translations.getString("MenuEdit"));
		MenuHelp.setText(translations.getString("MenuHelp"));
		MenuFileOpenCd.setText(translations.getString("MenuFileOpenCd"));
		MenuFileOpenCdImage.setText(translations.getString("MenuFileOpenCdImage"));
		MenuFileUseBios.setText(translations.getString("MenuFileUseBios"));
		MenuFileExit.setText(translations.getString("MenuFileExit"));
		MenuEditPreferences.setText(translations.getString("MenuEditPreferences"));
		MenuHelpAbout.setText(translations.getString("MenuHelpAbout"));
	}

	private void LoadRecentImages() {
		String cur = null;
		int next = 0;

		Boolean NeedSeparator = false;

		while (true) {
			cur = Engine.Config.getConfig("Recent" + next);

			if (cur == null) {
				break;
			} else {
				File tmp = new File(cur);
				if (!tmp.exists()) {
					next++;
					continue;
				}

				NeedSeparator = true;
				String fn = tmp.getName();

				javax.swing.JMenuItem Recent = new javax.swing.JMenuItem(fn);
				MenuFile.add(Recent, 4 + next);

				/* For some reason the actionlistener wants a final variable */
				final String copy = cur;
				Recent.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						System.out.println("Recent: " + copy);
					}
				});
			}

			next++;
		}

		if (NeedSeparator) {
			javax.swing.JSeparator s = new javax.swing.JSeparator();
			MenuFile.add(s, 4);
		}
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
        private void initComponents() {

                jFileChooser1 = new javax.swing.JFileChooser();
                jMenuBar1 = new javax.swing.JMenuBar();
                MenuFile = new javax.swing.JMenu();
                MenuFileOpenCd = new javax.swing.JMenuItem();
                MenuFileOpenCdImage = new javax.swing.JMenuItem();
                jSeparator2 = new javax.swing.JSeparator();
                MenuFileUseBios = new javax.swing.JCheckBoxMenuItem();
                jSeparator1 = new javax.swing.JSeparator();
                MenuFileExit = new javax.swing.JMenuItem();
                MenuEdit = new javax.swing.JMenu();
                MenuEditPreferences = new javax.swing.JMenuItem();
                MenuLanguage = new javax.swing.JMenu();
                MenuHelp = new javax.swing.JMenu();
                MenuHelpAbout = new javax.swing.JMenuItem();

                setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
                addWindowListener(new java.awt.event.WindowAdapter() {
                        public void windowClosing(java.awt.event.WindowEvent evt) {
                                doExit(evt);
                        }
                });

                MenuFile.setText("File");

                MenuFileOpenCd.setText("Open CD-ROM");
                MenuFile.add(MenuFileOpenCd);

                MenuFileOpenCdImage.setText("Open CD-ROM image");
                MenuFileOpenCdImage.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                MenuFileOpenCdImageActionPerformed(evt);
                        }
                });
                MenuFile.add(MenuFileOpenCdImage);
                MenuFile.add(jSeparator2);

                MenuFileUseBios.setSelected(true);
                MenuFileUseBios.setText("Use BIOS");
                MenuFile.add(MenuFileUseBios);
                MenuFile.add(jSeparator1);

                MenuFileExit.setText("Exit");
                MenuFileExit.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                MenuFileExitActionPerformed(evt);
                        }
                });
                MenuFile.add(MenuFileExit);

                jMenuBar1.add(MenuFile);

                MenuEdit.setText("Edit");

                MenuEditPreferences.setText("Preferences");
                MenuEditPreferences.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                MenuEditPreferencesActionPerformed(evt);
                        }
                });
                MenuEdit.add(MenuEditPreferences);

                jMenuBar1.add(MenuEdit);

                MenuLanguage.setText("Language");
                jMenuBar1.add(MenuLanguage);

                MenuHelp.setText("Help");

                MenuHelpAbout.setText("About...");
                MenuHelpAbout.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                                MenuHelpAboutActionPerformed(evt);
                        }
                });
                MenuHelp.add(MenuHelpAbout);

                jMenuBar1.add(MenuHelp);

                setJMenuBar(jMenuBar1);

                javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
                getContentPane().setLayout(layout);
                layout.setHorizontalGroup(
                        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 589, Short.MAX_VALUE)
                );
                layout.setVerticalGroup(
                        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 421, Short.MAX_VALUE)
                );

                pack();
        }// </editor-fold>//GEN-END:initComponents

	private void doExit(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_doExit
		Engine.Config.Save();
		System.exit(0);
	}//GEN-LAST:event_doExit

	private void MenuHelpAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MenuHelpAboutActionPerformed
		AboutFrame f = new AboutFrame();
		f.setVisible(true);
	}//GEN-LAST:event_MenuHelpAboutActionPerformed

	private void MenuFileExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MenuFileExitActionPerformed
		doExit(null);
	}//GEN-LAST:event_MenuFileExitActionPerformed

	private void MenuFileOpenCdImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MenuFileOpenCdImageActionPerformed
		jFileChooser1.setCurrentDirectory(new File("Z:\\Scrivania\\Ps1"));
		int result = jFileChooser1.showDialog(MenuEdit, translations.getString("OpenImageApprovation"));
		if (result == javax.swing.JFileChooser.APPROVE_OPTION) {
			File f = jFileChooser1.getSelectedFile();
			ImageFormats.ImageFormat p = new ImageFormats.Iso9660.IsoParser();

			try {
				p.Init(f.getPath());
				PlayStation = new Engine.Ps1();
				PlayStation.Init(p);
				PlayStation.Start();
			} catch (Exception ex) {
				System.out.println("Unable to initialize the emulator: " + ex.getMessage());
				return;
			}
		}

	}//GEN-LAST:event_MenuFileOpenCdImageActionPerformed

	private void MenuEditPreferencesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MenuEditPreferencesActionPerformed
		new Preferences().setVisible(true);
	}//GEN-LAST:event_MenuEditPreferencesActionPerformed

	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new MainFrame().setVisible(true);
			}
		});
	}
        // Variables declaration - do not modify//GEN-BEGIN:variables
        private javax.swing.JMenu MenuEdit;
        private javax.swing.JMenuItem MenuEditPreferences;
        private javax.swing.JMenu MenuFile;
        private javax.swing.JMenuItem MenuFileExit;
        private javax.swing.JMenuItem MenuFileOpenCd;
        private javax.swing.JMenuItem MenuFileOpenCdImage;
        private javax.swing.JCheckBoxMenuItem MenuFileUseBios;
        private javax.swing.JMenu MenuHelp;
        private javax.swing.JMenuItem MenuHelpAbout;
        private javax.swing.JMenu MenuLanguage;
        private javax.swing.JFileChooser jFileChooser1;
        private javax.swing.JMenuBar jMenuBar1;
        private javax.swing.JSeparator jSeparator1;
        private javax.swing.JSeparator jSeparator2;
        // End of variables declaration//GEN-END:variables
}
